<template>
  <div class="verification-code-container">
    <el-form :model="formData" :rules="rules" ref="formRef">
      <el-form-item prop="phone">
        <el-input v-model="formData.phone" type="tel" maxlength="11" placeholder="请输入手机号"  :style="inputStyle" />
      </el-form-item>

      <el-form-item prop="pcode" class="code-input-group">
        <el-input v-model="formData.pcode" placeholder="请输入验证码" :style="inputStyle" />
        <el-button link :disabled="isGettingCode" class="get-code-btn" @click="getVerificationCode">
          {{ codeButtonText }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <RegisterInfo v-if="!userStore?.saveRegisterInfo?.rePhone" :loginCommit="formData"></RegisterInfo>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin" style="width: 100%; height: 44px; background-color: #126983; color: #ffffff; font-size: 16px"
          >登录</el-button
        >
      </el-form-item>
    </el-form>

    <el-alert v-if="showError" title="登录失败" type="error" description="手机号未注册或验证码错误" show-icon :closable="false" class="error-alert" />
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits, defineProps } from "vue";
import { ElMessage } from "element-plus";
import { handleSubmitCaptche, handleCaptcheLogin, handleRegister } from "@/service/login.js";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/User.js";
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const formRef = ref(null);
const showError = ref(false);
const isGettingCode = ref(false);
const countdown = ref(60);
const codeButtonText = ref("获取验证码");
const formData = reactive({
  phone: "",
  pcode: "",
  tk: "",
  origin:1,
});

const plan_time = computed(()=>{
  const { year, month, day }  = userStore.saveRegisterInfo.plan_time

  if(year && month && day){
    return new Date(year, month - 1, day).getTime() / 1000
  }else{
    return 0
  }
})

const emit = defineEmits(["login"]);
const props = defineProps({
  isAgreeddValue: {
    type: Boolean,
    default: false,
  },
});
// console.log(route.path,'---')
const rules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" },
  ],
  pcode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 4, message: "验证码长度应为6位", trigger: "blur" },
  ],
};

// const isRegisterOrLogin=ref(true)
// const handleLogin = () => {
//     emit('login', {
const isRegistrerStatus=()=>{
  return  userStore.saveRegisterInfo.rePhone ? 1 : 2
}

const getVerificationCode = async () => {
  // console.log(route)
  // return false
  if (!formData.phone) {
    ElMessage.warning("请先输入手机号");
    return;
  }

  if (isGettingCode.value) {
    return false;
  }
  try {
    const res = await handleSubmitCaptche({
      phone: formData.phone,
      type:isRegistrerStatus(),
    });
    console.log("res.data t:>> ", res.data);
    formData.tk = res.data.tk;
    isGettingCode.value = true;

    if(res.code === '000000'){
      ElMessage.success('发送成功')
      codeButtonText.value = `${countdown.value}s`;
      const timer = setInterval(() => {
        countdown.value--;
        codeButtonText.value = `${countdown.value}s`;
        if (countdown.value <= 0) {
          clearInterval(timer);
          isGettingCode.value = false;
          codeButtonText.value = "获取验证码";
          countdown.value = 60;
        }
      }, 1000);
    }
  } catch (error) {
    // showError.value = true
  }

  
};

const handleLogin = async () => {
  // test
  //   if (!props.isAgreeddValue) {
  //     ElMessage.warning("请确认已阅读并同意《用户协议》");
  //     return false;
  //   }
  const regInfo = {
    ...userStore.saveRegisterInfo,
    ...formData,
  };

  let resp
  if(isRegistrerStatus()==1){
    resp = await handleRegister({
      ...regInfo,
      plan_time: plan_time.value,
      study_time: userStore?.saveRegisterInfo?.study_time || 0,
      list: userStore?.saveRegisterInfo?.is_exam == 1 
        ? userStore?.saveRegisterInfo?.list.map(i=>({...i, exam_time: i.exam_time.getTime() / 1000})) 
        : []
    });
  }else{
    resp = await handleCaptcheLogin({
      ...regInfo,
    })
  }

  if(resp.code === '000000'){
    console.log('loginStatus',resp,'---')
    emit('login',resp.data)
  }
 
  // console.log("resp :>> ", resp);
  // console.log("regInfo :>> ", regInfo);
  // if (!formRef.value) return;
  //  formRef.value.validate(async (valid) => {
  //     if (valid) {
  //        try{
  //         let response=await handleCaptcheLogin({
  //             tk:formData.tk.value,
  //             phone: formData.phone,
  //             code:formData.code
  //         })
  //         showError.value = false;
  //         ElMessage.success('登陆成功');
  //         //存取用户信息
  //         //更新界面弹窗取消
  //        
  //        }catch(error){
  //         showError.value = true;
  //        }

  //         // emit('login', {
  //         //     phone: formData.phone,
  //         //     code: formData.code
  //         // });

  //         // // 这里假设登录失败，实际应该根据接口返回决定
  //     }
  // });
};
const inputStyle = {
  backgroundColor: "#EEEEEE",
  height: "44px",
  "::placeholder": {
    fontSize: "14px",
  },
};
</script>

<style scoped lang="scss">
.verification-code-container {
  /* padding: 20px; */
  max-width: 400px;
  margin: 0 auto;
}

.code-input-group :deep(.el-form-item__content) {
  display: flex;
  gap: 10px;
  position: relative;
}

.get-code-btn {
  flex-shrink: 0;
  width: 120px;
  position: absolute;
  right: 10px;
  color: #126983;
}

.error-alert {
  margin-top: 20px;
}

.verification-code-container:deep(.el-form-item) {
  margin-bottom: 20px;
}

.verification-code-container :deep(.el-input__inner::placeholder) {
  font-size: 14px;
}

.verification-code-container :deep(.el-input__wrapper) {
  background-color: #eeeeee !important;
}
</style>
